/**
 * ref :: https://segmentfault.com/a/1190000003810652
 */

import "fetch-detector";
import Promise from "es6-promise";

export default (url, data = {})=> {
    if (url.indexOf('/login') > -1 && data.method == 'POST') {

        if (typeof data.body == 'object') {
            var tmp = [];
            console.log(JSON.stringify(data.body))
            data.body.url && (delete data.body.url);
            for (var pro in data.body) {
                (!!data.body[pro]) && tmp.push(pro + '=' + data.body[pro]);
            }
            url += url.indexOf('?') > -1 ? '&' : '?';
            url += tmp.join('&');
            data.body = JSON.stringify(data.body)
        }
        if ((!data.method || data.method.toUpperCase() == 'GET') && data.body) {
            delete data.body;
        }
    } else if (data.method == 'POST') {
        data.body = JSON.stringify(data.body)
    } else {
        if (typeof data.body == 'object') {
            var tmp = [];
            data.body.url && (delete data.body.url);
            for (var pro in data.body) {
                if (data.body[pro] == 0 || !!data.body[pro]) {
                    tmp.push(pro + '=' + data.body[pro])
                }
            }
            url += url.indexOf('?') > -1 ? '&' : '?';
            url += tmp.join('&');
            data.body = JSON.stringify(data.body)
        }
        if ((!data.method || data.method.toUpperCase() == 'GET') && data.body) {
            delete data.body;
        }
    }

    return new Promise((resolve, reject)=> {
        fetch(url, Object.assign({
            credentials: 'include', //enable cookie
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            cache: ''
        }, data))
            .then(res=> {
                if (res.headers.get("content-type") &&
                    res.headers.get("content-type").toLowerCase().indexOf("application/json") >= 0) {
                    return res.json()
                } else {
                    return res;
                }
            })
            .then(data=> {
                if ((data.status == 504) || (data.status == 500) || (data.status == 502)) {
                    alert(data.statusText);
                    console.log(JSON.stringify(data))
                } else if (data.result && '000000' == data.result.retCode) {
                    var tmp = {page: '', data: ''};
                    for (var pro in data.result.data) {
                        if (data.result.data[pro] instanceof Array) {
                            tmp[pro] = data.result.data[pro];
                            tmp.data = data.result.data[pro];
                            tmp.data = tmp.data.map((item, index) => {
                                if (typeof item == 'object') {
                                    item.index = index;
                                }
                                return item;
                            })
                        } else if (pro == 'page') {
                            tmp['pages'] = data.result.data[pro].totalPage;
                            tmp['total'] = data.result.data[pro].totalSize;
                            tmp['page'] = data.result.data[pro].currentPage;
                            tmp['size'] = data.result.data[pro].pageSize;
                            tmp['size'] = data.result.data[pro].pageSize;
                            tmp[pro + '_'] = data.result.data[pro];
                            tmp['page'] = data.result.data[pro].currentPage;
                            tmp['cpage'] = {
                                total: tmp['total'],
                                size: tmp['size'],
                                page: tmp['page'],
                                pages: tmp['pages'],
                            };
                        } else {
                            tmp[pro] = data.result.data[pro];
                        }
                    }
                    resolve(tmp)
                } else if (data.result && (data.result.retCode == '040003')) {


                    if (!(window.location.href.indexOf('debug') > -1)) {
                        window.location = '/login';
                    }

                } else if (data.result && (data.result.retCode == '000000')) {
                    resolve(data)
                } else if (data.result) {
                    if (data.result.retCode) {
                        alert(data.result.reason)
                    }
                    reject(data);
                }
            })
            .catch(e=> {
                new Error('Oops,error', e);
                if (!(window.location.href.indexOf('debug') > -1) && (window.location.href.indexOf('localhost') == -1)) {
                    window.location = '/login';
                }
            })
    })
};